package com.xnx3.kefu.superadmin.controller;

import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xnx3.j2ee.util.ActionLogUtil;
import com.xnx3.j2ee.util.Page;
import com.xnx3.j2ee.util.Sql;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.j2ee.entity.User;
import com.xnx3.j2ee.service.SqlCacheService;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.service.UserService;
import com.xnx3.kefu.core.Global;
import com.xnx3.kefu.core.entity.Kefu;
import com.xnx3.kefu.core.entity.Question;
import com.xnx3.kefu.core.entity.Zuoxi;
import com.xnx3.kefu.core.service.KefuService;
import com.xnx3.kefu.core.vo.KefuVO;

/**
 * 客服管理，管理当前平台的客服
 * @author 管雷鸣
 */
@Controller(value="KefuSuperadminKefuController")
@RequestMapping("/kefu/superadmin/")
public class KefuController extends BaseController {
	@Resource
	private UserService userService;
	@Resource
	private SqlService sqlService;
	@Resource
	private SqlCacheService sqlCacheService;
	@Resource
	private KefuService kefuService;
	
	

	/**
	 * 添加客服，开通
	 * @return
	 */
	@RequiresPermissions("adminKefu")
	@RequestMapping("add.do")
	public String add(HttpServletRequest request, Model model){
		ActionLogUtil.insert(request, "进入开通客服的页面");
		return "kefu/superadmin/add";
	}


	/**
	 * 添加客服，接收提交数据保存
	 * @param username 
	 * @param password 
	 */
	@RequiresPermissions("adminKefu")
	@RequestMapping("addSave.json")
	@ResponseBody
	public BaseVO addSubmit(HttpServletRequest request,
			@RequestParam(value = "username", required = false , defaultValue="") String username,
			@RequestParam(value = "password", required = false , defaultValue="") String password
			){
		
		//创建客服用户
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		
		//创建客服平台
		KefuVO kefuvo = kefuService.createKefu(user, request);
		if(kefuvo.getResult() - KefuVO.FAILURE == 0){
			return error(kefuvo.getInfo());
		}
		
		ActionLogUtil.insertUpdateDatabase(request, "通过后台创建客服完成", "kefuid:"+kefuvo.getKefu().getId());
		return success(kefuvo.getKefu().getId()+"");
	}
	

	/**
	 * 当前的客服平台列表
	 */
	@RequiresPermissions("adminKefu")
	@RequestMapping("list.do")
	public String subAgencyList(HttpServletRequest request, Model model){
		Sql sql = new Sql(request);
		sql.setSearchTable("user");
		sql.appendWhere("user.authority = '"+Global.ROLE_ID_ADMIN+"'");
		sql.setSearchColumn(new String[]{"username"});
		int count = sqlService.count("user", sql.getWhere());
		Page page = new Page(count, 15, request);
		sql.setSelectFromAndPage("SELECT user.id, user.username,user.lasttime, user.isfreeze, kefu.id AS kefuid FROM user LEFT JOIN kefu ON user.id = kefu.userid", page);
//		sql.appendWhere("kefu.userid = user.id");
		sql.setOrderByField(new String[]{"id","expiretime","addtime"});
		List<Map<String, Object>> list = sqlService.findMapBySql(sql);
		ActionLogUtil.insert(request, "查看客服列表");
		
		model.addAttribute("list", list);
		model.addAttribute("page", page);
		return "kefu/superadmin/list";
	}
	

	/**
	 * 暂停，冻结。冻结后，这个客服平台将无法登陆进入后台（包括这个客服平台下的坐席）
	 * @param kefuid 要冻结的客服id，对应 Kefu.id
	 */
	@RequiresPermissions("adminKefu")
	@RequestMapping("freeze.json")
	@ResponseBody
	public BaseVO freeze(HttpServletRequest request,
			@RequestParam(value = "kefuid", required = true) int kefuid){
		Kefu kefu = sqlService.findById(Kefu.class, kefuid);
//		User user = sqlService.findById(User.class, kefu.getuser);
//		if(user == null){
//			return error("用户不存在！");
//		}
//		//判断是否是其直属上级
//		if(user.getReferrerid() - getMyAgency().getUserid() != 0){
//			return error("要暂停的网站不是您的直属下级，操作失败");
//		}
//		//判断网站状态是否符合，只有当网站状态为正常时，才可以对网站进行暂停冻结操作
//		if(site.getState() - Site.STATE_NORMAL != 0){
//			return error("当前网站的状态不符，暂停失败");
//		}
		
		kefu.setFreeze(Kefu.FREEZE_YES);
		sqlService.save(kefu);
		//也冻结这个用户
		userService.freezeUser(kefu.getUserid());
		
		//记录操作日志
		ActionLogUtil.insertUpdateDatabase(request, kefu.getId(), "将客服kefuid:"+kefu.getId()+"冻结");
		
		return success();
	}
	
	/**
	 * 解除冻结的客服，将暂停的客服恢复正常
	 * @param kefuid 要解除冻结的客服的kefu.id
	 */
	@RequiresPermissions("adminKefu")
	@RequestMapping("unFreeze.json")
	@ResponseBody
	public BaseVO unFreeze(HttpServletRequest request,
			@RequestParam(value = "kefuid", required = true) int kefuid){
		Kefu kefu = sqlService.findById(Kefu.class, kefuid);
		kefu.setFreeze(Kefu.FREEZE_NO);
		sqlService.save(kefu);
		
		//也解除冻结这个用户
		userService.unfreezeUser(kefu.getUserid());
		
		//记录操作日志
		ActionLogUtil.insertUpdateDatabase(request, kefu.getId(), "将客服kefuid:"+kefu.getId()+"解除冻结");
		
		return success();
	}
	

	/**
	 * 给某个客服更改密码
	 * @param userid 要更改密码的user.id
	 * @param newPassword 要更改上的新密码
	 */
	@RequiresPermissions("adminKefu")
	@RequestMapping("updatePassword.json")
	@ResponseBody
	public BaseVO updatePassword(HttpServletRequest request,
			@RequestParam(value = "userid", required = true) int userid,
			@RequestParam(value = "newPassword", required = true) String newPassword){
		User user = sqlService.findById(User.class, userid);
		if(user == null){
			return error("用户不存在");
		}
//		//判断是否是其直属下级
//		if(user.getReferrerid() - getMyAgency().getUserid() != 0){
//			return error("要更改密码的网站不是您的直属下级，操作失败");
//		}
		
		ActionLogUtil.insertUpdateDatabase(request, userid, "总后台给客服更改密码", newPassword);
		return userService.updatePassword(userid, newPassword);
	}
	

	/**
	 * 删除客服
	 * @param id kefu.id
	 */
	@RequiresPermissions("adminKefu")
	@RequestMapping(value="delete.json", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO delete(@RequestParam(value = "id", required = false, defaultValue="0") int id, HttpServletRequest request){
		Kefu kefu = sqlService.findById(Kefu.class, id);
		if(kefu == null) {
			return error("要删除的客服不存在");
		}
		
		//删除缓存相关
		sqlCacheService.deleteCacheById(Kefu.class, kefu.getId());
		sqlCacheService.deleteCacheByProperty(Kefu.class, "chatid", kefu.getChatid());
		
		//删除客服
		sqlService.delete(kefu);
		
		//删除坐席
		List<Zuoxi> zuoxiList = sqlService.findByProperty(Zuoxi.class, "kefuid", kefu.getId());
		for (int i = 0; i < zuoxiList.size(); i++) {
			Zuoxi zuoxi = zuoxiList.get(i);
			//删除坐席缓存
			sqlCacheService.deleteCacheById(Zuoxi.class, zuoxi.getId());
			//删除坐席用户
			sqlService.executeSql("DELETE FROM user WHERE id="+zuoxi.getUserid());
			
			//删除坐席本身
			sqlService.delete(zuoxi);
		}
		
		//记录操作日志
		ActionLogUtil.insertUpdateDatabase(request, kefu.getId(), "将客服kefuid:"+kefu.getId()+"删除");
		
		return success();
	}
}
